import axios from "axios";
import {ElMessage} from "element-plus";
import {loginStore} from "@/store/modules/loginStore.js";

const service = axios.create({
    baseURL: '/api',
    timeout: 5000,
})

// 请求拦截器
service.interceptors.request.use((config) => {
    // 获得 login store
    const store = loginStore()

    // 赋予header验证信息
    config.headers.Authorization = store.token
    return config
}, (error) => {
    return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use((response) => {
    const {data, meta} = response.data
    if (meta.status === 200 || meta.status === 201) {
        return data
    } else {
        ElMessage.error(meta.msg)
        return Promise.reject(new Error(meta.msg))
    }
}, error => {
    error.response && ElMessage.error(error.response.data)
    return Promise.reject(new Error(error.response.data))
})

export default service
